package com.ykh.mybbsdemo.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ykh.mybbsdemo.dao.mapper.CategoryMapper;
import com.ykh.mybbsdemo.dao.pojo.Category;
import com.ykh.mybbsdemo.service.CategoryService;
import com.ykh.mybbsdemo.vo.CategoryVo;
import com.ykh.mybbsdemo.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-08-31
 * Time: 20:06
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    /**
     * 根据categaryId查找categary ,
     * @param categoryId
     * @return
     */
    @Override
    public CategoryVo findCategoryById(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        CategoryVo categoryVo = new CategoryVo();
        //将category 转化为 categoryVo
        BeanUtils.copyProperties(category,categoryVo);
        categoryVo.setId( String.valueOf(category.getId()));
        return categoryVo;
    }

    //查找所有文章分类
    @Override
    public Result findAll() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Category::getId,Category::getCategoryName);
        //数据库查询获得文章列表
        List<Category> categories = categoryMapper.selectList(queryWrapper);

        //将其转换成josn对象
        return Result.success(copyList(categories));
    }
    //查找所有文章分类(字段详细)
    @Override
    public Result findAllDetail() {
        //数据库查询获得文章列表
        List<Category> categories = categoryMapper.selectList(null);
        //将其转换成josn对象
        return Result.success(copyList(categories));
    }

    /**
     * 根据分类ID查询分类的详细信息
     * @param id
     * @return
     */
    @Override
    public Result categoriesDetailById(Long id) {
        Category category = categoryMapper.selectById(id);
        CategoryVo categoryVo = copy(category);
        return Result.success(categoryVo);
    }

    public CategoryVo copy(Category category){
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setId( String.valueOf( category.getId()));
        BeanUtils.copyProperties(category,categoryVo);
        return categoryVo;
    }
    public List<CategoryVo> copyList(List<Category> categoryList){
        List<CategoryVo> categoryVoList = new ArrayList<>();

        for (Category category : categoryList) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }
}
